package com.app.project;

import com.app.DB.SegwayDetails;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class BESM_MainForAdmin  extends Activity 
								implements  GooglePlayServicesClient.ConnectionCallbacks,
											GooglePlayServicesClient.OnConnectionFailedListener,
											LocationListener,
											OnMapClickListener, 
											OnMapLongClickListener, 
											OnMarkerClickListener {
	
	private ListView mDataView;
	private ArrayAdapter<String> mArrayAdapter;
	
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private Boolean UpdatetoServer = false;
	private static final int END = 0;
	private static final int UPDATE = 1;
	private int OPERATION ;
	private String ServiceOID ;
	
	// -------------Map----------------------//
	private LocationClient mLocationclient;
	private Location mCurrentLocation;
	private GoogleMap map;
//    private LocationManager locationManager;
//    private String provider;
    private double lat;
    private double lng;
    private LatLng currentLanLng;
    private String msg;
    private LocationRequest request;
    private MarkerOptions MarkerMe;
    Double[] AREADRAW;
    boolean markerClicked = false;
//    private PolygonOptions polygonOptions;
//    PolygonOptions area;
//    private Polygon polygon;
//    private long expiration=-1;
//    private PendingIntent mFireintent;
//    private Intent mIntent;
    
//    private MarkerOptions MarkerOther;
    // -------------User_Interface----------------------//
    EditText CarID,CarBattery,CarBalance,CarLocation;
    Button buttonB,buttonS,buttonClear;
    ImageView ImageUser;
    
//	Stack<String> st = new Stack<String>();
    
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_map);
		
		
		
		CarID = (EditText) findViewById(R.id.A_Main_carid);
	    CarBattery = (EditText) findViewById(R.id.A_Main_battery);
	    CarBalance = (EditText) findViewById(R.id.A_Main_Balance);
//	    CarLocation = (EditText) findViewById(R.id.A_Main_location);
	    buttonB = (Button)findViewById(R.id.A_Main_buttonB);
	    buttonB.setOnClickListener(LatsLocation);
	    buttonS = (Button)findViewById(R.id.A_Main_buttonS);
//	    buttonS.setOnClickListener(SentCommanS);
	    buttonClear = (Button)findViewById(R.id.A_Main_buttonClear);
//	    buttonClear.setOnClickListener(Clear);
	    ImageUser = (ImageView)findViewById(R.id.A_Main_imageuser);
	    ImageUser.setOnClickListener(LatsLocation);
	    
		mArrayAdapter = new ArrayAdapter<String>(this, R.layout.databluetooth);
		mDataView = (ListView) findViewById(R.id.A_Main_listmessage);
		mDataView.setAdapter(mArrayAdapter);
		
//		mIntent = new Intent("You entered the defined area");
//		mFireintent = PendingIntent.getBroadcast(this, -1, mIntent, 0);
		
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.Map_Map)).getMap();
		//map.setMyLocationEnabled(true);
	    map.setIndoorEnabled(true);
	    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
	    map.setOnMapClickListener(this);
	    map.setOnMapLongClickListener(this);
	    map.setOnMarkerClickListener(this);
	    
		mLocationclient = new LocationClient(this,this,this);
		
		request = LocationRequest.create();
		request.setInterval(1000);
		request.setFastestInterval(1000);
//		request.setSmallestDisplacement((float) 2.0);
		request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		
		MarkerMe = new MarkerOptions();
		MarkerMe.title("Admin");
		MarkerMe.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		
	
		
	}
	
	public void onStart(){
		super.onStart();
		Toast.makeText(BESM_MainForAdmin.this, "In the onStart() event",
             Toast.LENGTH_SHORT).show();
		mLocationclient.connect();
	}
	
	
	public void onStop(){
		Toast.makeText(BESM_MainForAdmin.this, "In the onStop() event",
                Toast.LENGTH_SHORT).show();
		mLocationclient.disconnect();
		super.onStop();
		
	}
	
	public void onPause(){
		super.onPause();
		Toast.makeText(BESM_MainForAdmin.this, "In the onPause() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onRestart(){
		super.onRestart();
		Toast.makeText(BESM_MainForAdmin.this, "In the onRestart() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onDestroy(){
		super.onDestroy();
		Toast.makeText(BESM_MainForAdmin.this, "In the onDestroy() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onResume() {
		super.onResume();
		Toast.makeText(BESM_MainForAdmin.this, "In the onResume() event",
	             Toast.LENGTH_SHORT).show();
    
	}
	
	public void LatsLocation(){
		// ตรวจสอบการเชื่อมต่อว่าเชื่อมต่อ Location Services แล้ว
		if(mLocationclient.isConnected()){
    		map.clear(); //ลบหมุดเดิม
    		// ขอตำแหน่งปัจจุบันจาก Location จาก Location Service
    		mCurrentLocation = mLocationclient.getLastLocation();
    		// หาพิกัด 
    		lat = mCurrentLocation.getLatitude();
    		lng = mCurrentLocation.getLongitude();
    		
    		// สร้างออบเจ็ค LatLng เก็บค่าพิกัด
    		currentLanLng = new LatLng(lat, lng);
    		// ย้ายกล้อง เเละปักหมุด
    		map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLanLng,18));
    		map.addMarker(MarkerMe.position(currentLanLng));
    		msg = "Current location: "+String.valueOf(lat)+","+String.valueOf(lng);
        	
    	}else{
    		msg = "Cannot Connect Location";
    	}
		//locationManager.addProximityAlert(lat, lng, 500f, -1, mFireintent);
    	mLocationclient.requestLocationUpdates(request, BESM_MainForAdmin.this);
	}
	private OnClickListener LatsLocation = new OnClickListener() {
	        public void onClick(View v) {
	        	LatsLocation();
	        }
	}; 

	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
	
	//-----------InsertService-Loading----------------------------------//
    public class InsertService extends AsyncTask<String, Void, Void> {
        @SuppressWarnings("deprecation")
		protected void onPreExecute() {
        	super.onPreExecute();
        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
        	
        	switch (OPERATION){
        		case END:
        			SegwayDetails usr = new SegwayDetails(
        					ServiceOID,
                			null,
                			null,
            				"1",
            				null,	
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				null
            		);
            		try {
        				if(usr.OperationData("End") != null){
        					UpdatetoServer = true;
        				}
        			} catch (Exception e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			break;
        			
        		case UPDATE:
        			
        			break;
        		default:
    	            return null;
        	}
        	
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
            if(UpdatetoServer){
            	
            }
        	
        }
        
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	 @Override
		public void onBackPressed() {
		  
		        new AlertDialog.Builder(this)
		        .setTitle("ออกจากโปรแกรม")
		        .setMessage("ต้องการออกจากโปรแกรม")
		                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
		                    	Intent intent = new Intent(BESM_MainForAdmin.this,BESM_LoginActivity.class);
		                    	startActivity(intent);
		                    	
		                		OPERATION=END;
//		                		new  InsertService().execute();
		                        finish();
		                    }
		                })
		                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                    	
		                    }
		                }).create().show();
		}

	 
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		Toast.makeText(BESM_MainForAdmin.this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onConnected(Bundle data) {
		// TODO Auto-generated method stub
		Toast.makeText(BESM_MainForAdmin.this, "onConnected", Toast.LENGTH_SHORT).show();
		LatsLocation();	
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		Toast.makeText(BESM_MainForAdmin.this, "onDisconnected", Toast.LENGTH_SHORT).show();
	} 
	 
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		map.clear();
		drawOnmap();
//		LatLng a = new LatLng(13.85275,100.56654);
//		map.addMarker(MarkerMe.position(a));
		lat = location.getLatitude();
		lng = location.getLongitude();
		// สร้างออบเจ็ค LatLng เก็บค่าพิกัด
		currentLanLng = new LatLng(lat, lng);
		// ย้ายกล้อง เเละปักหมุด
		map.animateCamera(CameraUpdateFactory.newLatLng(currentLanLng));
		map.addMarker(MarkerMe.position(currentLanLng));
		msg = String.valueOf(lat)+"\n"+String.valueOf(lng);

		CarLocation.setText(msg);
		
	}  
	 	
	public void drawOnmap(){
		PolygonOptions area = new PolygonOptions();
		AREADRAW = new Double[] {
				18.804671,98.9745332,
				18.804851,98.9768982,
				18.802796,98.9769042,
				18.802978,98.9743967
				};
		msg = String.valueOf(AREADRAW.length);
		CarBattery.setText(msg);
		int i=0;
		int j=Integer.valueOf(AREADRAW.length);
		while(i<AREADRAW.length-1){
			area.add(new LatLng(Double.valueOf(AREADRAW[i]),Double.valueOf(AREADRAW[i+1])));
			i=i+2;
		}
		CarBattery.setText(msg);

		area.strokeWidth(3);
		area.strokeColor(Color.BLUE);
		area.fillColor(Color.argb(64, 0, 255, 0));
		map.addPolygon(area);
		//CarBattery.setText(AREA.length);
	}
	
	@Override
	public void onMapClick(LatLng point) {
		
	    map.animateCamera(CameraUpdateFactory.newLatLng(point));

	    markerClicked = false;
	}

	@Override
	public void onMapLongClick(LatLng point) {
//		tvLocInfo.setText("New marker added@" + point.toString());
		if(mLocationclient.isConnected()){
			mLocationclient.removeLocationUpdates(BESM_MainForAdmin.this);
		}
		map.addMarker(new MarkerOptions().position(point).title(point.toString()));
	    markerClicked = false;
	}

	@Override
	public boolean onMarkerClick(Marker maker) {
		// TODO Auto-generated method stub
		
//		if(markerClicked){
//
//	        if(polygon != null){
//	            polygon.remove();
//	            polygon = null;
//	        }
//
//	        polygonOptions.add(MarkerMe.getPosition());
//	        polygonOptions.strokeColor(Color.RED);
//	        polygonOptions.fillColor(Color.BLUE);
//	        polygon = map.addPolygon(polygonOptions);
//	    }else{
//	        if(polygon != null){
//	            polygon.remove();
//	            polygon = null;
//	        }
//
//	        polygonOptions = new PolygonOptions().add(MarkerMe.getPosition());
//	        markerClicked = true;
//	    }
		return false;
	}
}
